<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #canvas {
      box-shadow: 2px 4px 6px #eee;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
<script src="../script/utils.js"></script>
<script src="../components/Arrow.js"></script> 
<script>
  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d')
  
  const W = canvas.width = 800
  const H = canvas.height = 600

  let mouse = C.getOffset(canvas)

  // canvas.onclick = function () {
  //   console.log(mouse.x, mouse.y)
  // }
  let vx = 0, vy = 0, vr = 0, a = 0, w = 46, h = 20, f = 0.9

  const arrow = new Arrow({
    x: W / 2,
    y: H / 2,
    w,
    h
  }).render(ctx)

  window.addEventListener('keydown', function (e) {
    switch (e.keyCode) {
      case 37:
        vr = -5
        break;
      case 39:
        vr = 5
        break;
      case 38:
        a = 0.5
        break;
    }
  })
  window.addEventListener('keyup', function (e) {
    a = 0
    vr = 0
  })

  function move() {
    window.requestAnimationFrame(move)
    ctx.clearRect(0, 0, W, H)

    arrow.rotation += C.toRad(vr)
    let angle = arrow.rotation
    let ax = Math.cos(angle) * a
    let ay = Math.sin(angle) * a
    vx += ax
    vy += ay
    
    vx *= f
    vy *= f

    arrow.x += vx
    arrow.y += vy

    if (arrow.x - arrow.w / 2 >= W) {
      arrow.x = 0 - arrow.w / 2
    } else if (arrow.x + arrow.w / 2 <= 0) {
      arrow.x = arrow.w / 2 + W
    }

    arrow.render(ctx)
  }

  move()
</script>
</html>